<template>
  <div class="main-container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content-container">
      <div class="title-container">
        <div class="title-text">
          睡眠状态
        </div>
      </div>
      <div class="sleep-status-container">
        <div class="sleep-status-content">
          <div class="sleep-info-column">
            <div class="sleep-proportion-container">
              <div class="sleep-proportion-content">
                <div class="proportion-title">
                  <el-text class="proportion-text">睡眠占比：</el-text>
                </div>
                <div class="proportion-graph">
                  <div class="sleepInfoGraph" id="sleepStatusGraph"></div>
                </div>
                <div class="rem-info">
                  <font-awesome-icon :icon="['fas','fa-lightbulb']" size="2x" class="rem-icon"></font-awesome-icon>
                  <div class="rem-text-container">
                    <el-text class="rem-text">REM:快速眼球运动状态。是睡眠的一个阶段，眼球在这个阶段会呈现不由自主的快速运动</el-text>
                  </div>
                </div>
              </div>
            </div>
            <div class="sleep-stage-title">
              睡眠分期图
            </div>
          </div>
          <div class="sleep-analysis-column">
            <div class="analysis-title">
              <el-text class="analysis-text">睡眠分析：</el-text>
            </div>
            <div class="radar-graph">
              <div id="sleepRadarGraph" class="sleepRadarGraph"></div>
            </div>
            <div class="summary-container" >
              <div class="summary-item-up">
                <div class="summary-item-icon" >
                  <font-awesome-icon :icon="['fas','fa-calendar-alt']" size="2x" style="color: deepskyblue;"></font-awesome-icon>
                </div>
                <div class="summary-text-container">
                  <el-text class="summary-text">总睡眠间期时间：{{ currentUserSleepStateData.stateInfo.totalTime }}分钟</el-text>
                  <el-text class="summary-text">REM持续时间：{{ currentUserSleepStateData.stateInfo.remtime }}分钟</el-text>
                </div>
              </div>
              <div class="summary-item-down">
                <div class="summary-item-icon">
                  <font-awesome-icon :icon="['fas','fa-lightbulb']" size="2x" style="color: #FDB800;"></font-awesome-icon>
                </div>
                <div class="summary-text-container">
                  <el-text class="summary-text">总睡眠间期时间:从入睡开始到最后一个睡眠周期结束的总时间</el-text>
                  <el-text class="summary-text">总睡眠时间:总睡眠时间减去之中觉醒时间</el-text>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="sleep-stage-wrapper">
        <div class="sleep-stage-content">
          <div id="sleepStageChart" class="sleepStageGraph"></div>
        </div>
      </div>
      <div class="evaluation-wrapper">
        <div class="evaluation-content">
          <div class="evaluation-header">
            <div class="icon">
              <font-awesome-icon :icon="['fas','fa-file-alt']" size="2x" class="icon-color"></font-awesome-icon>
            </div>
            <div class="evaluation-title">
              <el-text class="evaluation-title-text">睡眠评估结果：</el-text>
            </div>
            <el-button v-if="enableEdit" class="edit-button" @click="showEditInput">
              <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
              <el-text class="edit-text">编辑</el-text>
            </el-button>
          </div>
          <div class="evaluation-body">
            <el-input type="textarea" class="evaluation-input" v-model="currentUserSleepStateData.evaluation" v-if="editMode"></el-input>
            <el-text v-else :span="24" class="evaluation-display">
              {{ currentUserSleepStateData.evaluation }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import '@/assets/css/reportCard.css';
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {ref, onMounted, onUnmounted, watch, markRaw} from "vue";
import * as echarts from "echarts";
import sleepData from "@/api/sleepData.js";
onMounted(() => {
  getSleepStateData(props.currentReportId);
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts);
});
onUnmounted(()=>{
  if (currentUserSleepStateData.value.evaluation === evaluationBackup.value){

  }else {
    const updateSleepStateDto = {
      reportId: props.currentReportId,
      evaluation: currentUserSleepStateData.value.evaluation
    }
    sleepData.updateSleepStateEvaluate(updateSleepStateDto).then((res)=>{
      if (res.data.code === 200){

      }
    }).catch((err)=>{
      console.log(err)
    })
  }
  disposeChart()
})
const props = defineProps({
  currentReportId: Number,
  enableEdit:Boolean
});
watch(() => props.currentReportId, (newId) => {
  getSleepStateData(newId);
});
watch(() => props.enableEdit, (newValue) => {
  enableEdit.value = newValue
});
const enableEdit = ref(props.enableEdit)
const loading = ref(false)
const evaluationBackup = ref('')
const getSleepStateData = (reportId)=>{
  loading.value = false;
  sleepData.getSleepStateData(reportId).then((res)=>{
    if (res.data.code === 200){
      currentUserSleepStateData.value = res.data.data
      evaluationBackup.value = currentUserSleepStateData.value.evaluation
      sleepChartData.value = currentUserSleepStateData.value.proportionList
      const stateInfo = currentUserSleepStateData.value.stateInfo
      createSleepChart();
      createSRChart(stateInfo);
      // 预处理数据
      const timeArray = currentUserSleepStateData.value.stateTime.times;
      const sleepStateArray = currentUserSleepStateData.value.stateTime.sleepStates;
      // 将时间和状态组合成对象
      const combinedData = timeArray.map((timestamp, index) => ({
        time: timestamp,
        state: sleepStateArray[index]
      }));
      // 按照时间进行排序
      combinedData.sort((a, b) => a.time - b.time);
      createSSChart(combinedData);
    }
  }).catch((err)=>{
    console.log(err)
  }).finally(() => {
    loading.value = false; // 使用箭头函数包装
  });
}
const sleepChartData = ref([
  {
    "name": "熟睡",
    "value": 0.333
  },
  {
    "name": "浅睡",
    "value": 0.333
  },
  {
    "name": "REM",
    "value": 0.333
  }
])

//图表创建
const sleepChartInstance = ref(null)
const SRChartInstance = ref(null);
const SSChartInstance = ref(null);
//睡眠占比图表
const createSleepChart = () => {
  sleepChartInstance.value = markRaw(echarts.init(document.getElementById("sleepStatusGraph")));
  sleepChartInstance.value.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {d}%'
    },
    legend: {
      show:false,
      orient: 'vertical',
      right: '0%',
      // top: 'center',
      textStyle: {
        color: 'black',
      },
      formatter: (name) => {
        let item = sleepChartData.value.find(item => item.name === name);
        let total = sleepChartData.value.reduce((acc, curr) => acc + curr.value, 0);
        let percent = 0;
        if (!isNaN(item.value) && !isNaN(total) && total !== 0) {
          percent = ((item.value / total) * 100).toFixed(0);
        }
        //let percent = ((item.value / total) * 100).toFixed(0);
        return `${name}: ${percent}%`;
      },
      data: sleepChartData.value.map(item => ({
        name: item.name,
        icon: 'circle'
      }))
    },
    series: [
      {
        name: '睡眠时长',
        type: 'pie',
        center: ['50%', '50%'], // 调整中心位置
        data: sleepChartData.value.map(item => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color
          }
        })),
        labelLine: {
          show: true  // 设置为 true 显示扇形上的延伸线
        },
        label: {
          show: true,
          formatter: '{b}\n{d}%',
          position: 'outside',
          width:80,
          overflow:"break",
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }, true);
};
//睡眠雷达图表
const createSRChart = (stateInfo) => {
  const stateInfoValues = [
    stateInfo.totalTime,
    stateInfo.lightSleepTime,
    stateInfo.deepSleepTime,
    stateInfo.awakeNum,
    stateInfo.fallAsleepTime
  ];
  SRChartInstance.value = markRaw(echarts.init(document.getElementById("sleepRadarGraph")));
  SRChartInstance.value.setOption({
    tooltip: {},
    legend: {
      data: ['标准良好睡眠状态参照', '用户实际睡眠状态'],
      top: 0,
      // left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 10
      }
    },
    radar: {
      indicator: [
        { name: '总睡眠时间', max: 500 },
        { name: '浅睡持续时间', max: 300 },
        { name: '深睡持续时间', max: 150 },
        { name: '清醒次数', max: 20 },
        { name: '入睡时间', max: 30 }
      ],
      radius: '40%',
      center: ['50%', '60%'],
      splitNumber: 5,
      shape: 'circle',
      name: {
        textStyle: {
          color: '#333',
          backgroundColor: '#fff',
          borderRadius: 3,
          padding: [3, 5]
        }
      },
      splitLine: {
        lineStyle: {
          color: [
            'rgba(238, 197, 102, 0.5)',
            'rgba(238, 197, 102, 0.4)',
            'rgba(238, 197, 102, 0.3)',
            'rgba(238, 197, 102, 0.2)',
            'rgba(238, 197, 102, 0.1)',
            'rgba(238, 197, 102, 0.05)'
          ].reverse()
        }
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(255, 255, 255, 0.1)']
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(238, 197, 102, 0.5)'
        }
      }
    },
    series: [{
      name: '标准良好睡眠状态参照',
      type: 'radar',
      data: [
        {
          value: [375.1, 207.5, 81.5, 15, 13.5],
          name: '标准良好睡眠状态参照',
          lineStyle: {
            color: 'rgba(0, 128, 255, 0.6)' // 修改边框颜色
          },
          areaStyle: {
            color: 'rgba(0, 128, 255, 0.3)' // 修改填充颜色
          }
        }
      ]
    }, {
      name: '用户实际睡眠状态',
      type: 'radar',
      data: [
        {
          value: stateInfoValues,
          name: '用户实际睡眠状态',
          lineStyle: {
            color: 'rgba(255, 69, 0, 0.6)' // 修改边框颜色
          },
          areaStyle: {
            color: 'rgba(255, 69, 0, 0.3)' // 修改填充颜色
          }
        }
      ]
    }]
  }, true);
};
//睡眠分析图表
const createSSChart = (combinedData) => {
  SSChartInstance.value = markRaw(echarts.init(document.getElementById("sleepStageChart"), "purple-passion"));
  SSChartInstance.value.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '10%', // 调整top值
      bottom: '5%', // 调整bottom值
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function (params) {
        var data = params[0].data;
        return `时间: ${data[0]}<br>状态: ${data[1]}`;
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: true, // 设置boundaryGap为true
      data: combinedData.map(data => formatTime(data.time)), // 使用排序后的时间数组
    },
    yAxis: {
      type: 'category',
      data: ['觉醒', '浅睡', '熟睡', 'REM'],
    },
    series: [
      {
        name: '睡眠状态',
        type: 'line',
        step: 'middle',
        data: combinedData.map(data => [formatTime(data.time), data.state]), // 使用排序后的组合数据
        symbol: 'none', // 隐藏圆点
      },
    ],
  },true);
};

//图表自适应
const resizeCharts = () => {
  if (sleepChartInstance.value) {
    sleepChartInstance.value.resize();
  }
  if (SRChartInstance.value) {
    SRChartInstance.value.resize();
  }
  if (SSChartInstance.value) {
    SSChartInstance.value.resize();
  }
};
const disposeChart = ()=>{
  if (sleepChartInstance.value) {
    sleepChartInstance.value.dispose();
  }
  if (SRChartInstance.value) {
    SRChartInstance.value.dispose();
  }
  if (SSChartInstance.value) {
    SSChartInstance.value.dispose();
  }
  // 移除事件监听器
  window.removeEventListener('resize', resizeCharts);
}

const editMode = ref(false)
const showEditInput = () => {
  editMode.value = !editMode.value;
};
const currentUserSleepStateData = ref({
  proportionList:[],
  stateInfo: {
    totalTime:'',
    fallAsleepTime:'',
    lightSleepTime:'',
    deepSleepTime:'',
    awakeNum:'',
    totalIntervalSleepTime:'',
    remtime:'',
  },
  evaluation:''
})
// 将时间戳格式化为可读的时间字符串
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  // 获取小时和分钟
  const hours = date.getHours().toString().padStart(2, '0'); // 补0操作，确保两位数
  const minutes = date.getMinutes().toString().padStart(2, '0');
  // 返回格式化后的时间字符串
  return hours + ':' + minutes;
};

</script>
<style scoped>
.main-container{
  width: 90%;height: 100%;background-color: #EFF2F9;border-radius: 20px
}
.content-container{
  width: 100%;height: 100%;display: flex;flex-direction: column
}
.title-container{
  width: 100%;height: 5%;margin-top: 2%
}
.title-text{
  font-size: 18px;height: 100%;margin-left: 20px;align-items: center;display: flex
}
.sleep-status-container{
  width: 100%;height: 50%;display: flex;align-items: center;justify-content: center
}
.sleep-status-content{
  height: 100%;width: 95%;;display: flex;
}
.sleep-info-column {
  width: 50%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.sleep-proportion-container {
  width: 90%;
  height: 80%;
  background-color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.sleep-proportion-content {
  width: 90%;
  height: 90%;
  display: flex;
  flex-direction: column;
}
.proportion-title {
  width: 100%;
  height: 10%;
  /*margin-top: 20px;*/
}
.proportion-text {
  font-size: 16px;
}
.proportion-graph {
  width: 100%;
  height: 75%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.rem-info {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
}
.rem-icon {
  color: #FDB800;
}
.rem-text-container {
  height: 100%;
  margin-left: 10px;
  /*overflow: hidden;*/
}
.rem-text {
  font-size: small;
  overflow: hidden;
}
@media (max-width: 1500px) {
  .rem-text {
    font-size: 12px;
  }
}
@media (max-width: 1200px) {
  .rem-text {
    font-size: 10px;
  }
}
.sleep-stage-title {
  width: 90%;
  height: 10%;
  font-size: 17px;
  margin-top: auto;
}
.sleep-analysis-column {
  width: 50%;
  height: 100%;
  background-color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.analysis-title {
  width: 100%;
  height: 10%;
  /*margin-top: 10px;*/
}
.analysis-text {
  font-size: 16px;
  margin-left: 20px;
}
.radar-graph {
  width: 100%;
  height: 63%;
}
.summary-container {
  width: 100%; height: 30%; background-color: #DCEFFE; border-radius: 0 0 20px 20px; display: flex; flex-direction: column; align-items: center; justify-content: center
}
.summary-item-up {
  width: 100%; height: 40%; display: flex; align-items: center;
}
.summary-item-down{
  width: 100%; height: 50%; display: flex; align-items: center;
}
.summary-item-icon{
  width: 40px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.summary-text-container {
  flex: 1; margin-left: 5px; display: flex; flex-direction: column;
  overflow: hidden;
}
.summary-text{
  width: 100%;
  font-size: 12px;
}
@media (max-width: 1500px) {
  .summary-text {
    font-size: 11px;
  }
}
@media (max-width: 1200px) {
  .summary-text {
    font-size: 10px;
  }
}
.sleepInfoGraph{
  margin-top: 2vh;
  width: 100%;
  height: 90%;
}
.sleepRadarGraph{
  margin-top: 1vh;
  width: 100%;
  height: 100%;
}
.sleepStageGraph{
  width: 38vw ;
  height: 15vh
}
.sleep-stage-wrapper {
  width: 100%;
  height: 30%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.sleep-stage-content {
  width: 95%;
  height: 90%;
  border-radius: 20px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
.sleepStageGraph {
  width: 100%;
  height: 100%;
}
.evaluation-wrapper {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  height: 100%;
  display: flex;
}
.evaluation-title-text {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}
</style>